package com.pearl.boot.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitOperations;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TangDan
 * @version 1.0
 * @since 2022/11/9
 */
@Configuration
public class MqBizConfig {

    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        configurer.configure(template, connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }


    public static final String BIZ_QUEUE = "bizQueue";

    public static final String BIZ_EXCHANGE = "bizExchange";

    public static final String BIZ_ROUTE_KEY = "biz.key";


    @Bean(BIZ_QUEUE)
    public Queue bizQueue() {
        return QueueBuilder.durable(BIZ_QUEUE).build();
    }

    @Bean(BIZ_EXCHANGE)
    public Exchange bizExchange() {
        // 使用alternate-exchange 设置备份交换机
        return ExchangeBuilder.directExchange(BIZ_EXCHANGE).withArgument("alternate-exchange", MqBackupConfig.BACKUP_EXCHANGE).durable(true).build();
    }

    @Bean("bizBinding")
    public Binding bizBinding(@Qualifier(BIZ_QUEUE) Queue bizQueue, @Qualifier(BIZ_EXCHANGE) Exchange bizExchange) {
        return BindingBuilder.bind(bizQueue).to(bizExchange).with(BIZ_ROUTE_KEY).noargs();
    }

}